// import { getMenuListApi } from '@/views/user/api/userApi';
import { ActionContext } from "vuex";
import { RootState } from "..";
import { RouteRecordRaw } from "vue-router";
const modules = import.meta.glob('../../views/**/**.vue')
export type MenuState = {
  isCollapse: boolean,
  menuList: any;
}
export const state = {
  isCollapse: false,//左边导航的收缩与展开
  menuList: []//菜单
}
export const mutations = {
  //设置 左边导航展开与收起
  setCollapse(state: MenuState, isCollapse: boolean) {
    state.isCollapse = isCollapse
  },
  setMenuList: (state: MenuState, menuList: Array<RouteRecordRaw>) => {
    state.menuList = menuList
  }
}
export const getters = {
  //获取 左边导航展开与收起
  getCollapse(state: MenuState) {
    return state.isCollapse
  },
  //获取路由导航
  getMenuList: (state: MenuState) => {
    return state.menuList
  }
}
//定义actions
export const actions = {
  getMenuList({ commit }: ActionContext<MenuState, RootState>, router: any) {
    // return new Promise((resolve, reject) => {
    //   getMenuListApi().then(res => {
    //     let accessedRoutes;
    //     if (res.code == 0) {
    //       //动态生成路由
    //       accessedRoutes = filterAsyncRoutes(res.data, router);
    //       //设置到menuList
    //       commit('setMenuList', accessedRoutes)
    //     }
    //     //返回
    //     resolve(accessedRoutes);
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  }
}

export function filterAsyncRoutes(routes: RouteRecordRaw[], router: any) {
  const res: Array<RouteRecordRaw> = [];
  routes.forEach((t: any) => {
    const names=t.menuUrl.split('/')
    let names2=''
    if(t?.children?.length>0){
      names2=t.children[0].menuUrl.split('/')
    }
    let path = names?.length>1&&t.menuUrl?t.menuUrl:'/'+names2[names2.length-2]
    let name = names?.length>1&&t.menuUrl?'/'+names[names.length-1]:'/'+names2[names2.length-2]
    const tmp = {
      path:path,
      component:t.menuUrl>1?t.menuUrl:'',
      name:name?name.substring(1,name.length):'',
      meta:{title:t.menuName},
      children:t.children
    }
    if (t.menuUrl) {
      tmp.component = modules[`../../views${t.menuUrl}.vue`]
    }else{
      tmp.component = modules['../../views/layout/layout.vue']
    }
    if (tmp?.children?.length>0) {
      //递归
      tmp.children = filterAsyncRoutes(tmp.children, router)
    }
    router.addRoute(tmp)
    res.push(tmp)
  })
  return res;
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}